package com.seecode;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.seecode.Adapter.FileAdapter;
import com.seecode.UnitClass.FileClass;
import com.seecode.Utils.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SearchActivity extends AppCompatActivity implements  View.OnClickListener{
    private ListView listView1;
    private List<FileClass> dataList1 = new ArrayList<FileClass>();
    private FileAdapter adapter1;
    private String leftDir="/";
    private String rightDir="/";
    private String currentDir="/";
    private TextView currentTitle;
    private ImageView leftLine;
    private Button    leftButton;
    private Button    rightButton;
    private ImageView rightLine;
    private int currentButton=0 ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);


        startInit();//init button and other
        listView1 =(ListView) findViewById(R.id.list1);
        dataInit();
        adapter1 = new FileAdapter(this,R.layout.file3,dataList1);
        listView1.setAdapter(adapter1);
        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long
                    id) {

               // String className = dataList.get(position);

                //Toast.makeText(HistoryActivity.this,className,Toast.LENGTH_SHORT).show();
                FileClass fileClass = dataList1.get(position);
                handleClick(fileClass);

            }
        });

    }
    public void startInit() {
        leftDir = Utils.getPreStrValues("leftDir");
        rightDir = Utils.getPreStrValues("rightDir");
        if(leftDir.equals("null")){
            leftDir="/";
        }
        if(rightDir.equals("null") || rightDir.equals("/")){

            rightDir= Environment.getExternalStorageDirectory().getPath();


        }

        currentDir=leftDir;
        leftButton =(Button)findViewById(R.id.leftButton);
        leftLine  =(ImageView)findViewById(R.id.leftLine);
        rightButton = (Button)findViewById(R.id.rightButton);
        rightLine = (ImageView)findViewById(R.id.rightLine);

        leftButton.setOnClickListener(this);
        rightButton.setOnClickListener(this);
        currentTitle =(TextView)findViewById(R.id.currentTitle);
            //set buttonline change
        currentTitle.setText(currentDir);
        LinearLayout.LayoutParams left;
        LinearLayout.LayoutParams right;
        left = (LinearLayout.LayoutParams) leftLine.getLayoutParams();
        left.height = 10;
        leftLine.setLayoutParams(left);
        right = (LinearLayout.LayoutParams) rightLine.getLayoutParams();
        right.height = 2;
        rightLine.setLayoutParams(right);

        /*if(!Utils.getPreBoolValues("isFirstInit")){

            Utils.remountDevPermission();
            Utils.setPreBoolValues("isFirstInit",true);
        }*/

        Logs.i("data upok on create");

    }

    public void handleClick(FileClass  fileClass){

        if(fileClass.getFileType() == 1){
            String openFile ;
            if(currentDir.equals("/")){

                openFile="/"+fileClass.getName();

            }else{
                openFile=currentDir+"/"+fileClass.getName();
            }
            Logs.i("you will open "+openFile);
            Utils.loadFile(openFile);
            Utils.setPreStrValues("leftDir",leftDir);
            Utils.setPreStrValues("rightDir",rightDir);
            finish();
        }else{
            String newDir = fileClass.getName();
            if(newDir.equals("..")){



                    int pos =currentDir.lastIndexOf("/");
                    if(pos == 0){
                                //if frst level is /xx  so it anser is 0 must add1 other ok
                        pos=1;
                    }
                    newDir = currentDir.substring(0,pos);

            }else{
                    if(currentDir.equals("/")){
                        newDir = currentDir+newDir; ///xx/bb
                    }else{
                        newDir = currentDir+"/"+newDir; ///xx/bb
                    }



            }
            currentDir=newDir;

            currentTitle.setText(currentDir);
            String buttonTitle;
            if(newDir.equals("/")) {
                buttonTitle="/";
            }else{

                buttonTitle =newDir.substring(newDir.lastIndexOf("/")+1);
            }


            openDir(currentDir);
            adapter1.notifyDataSetChanged();
            if(currentButton ==0) {

                leftDir = newDir;
                leftButton.setText(buttonTitle);
            }else{
                rightDir = newDir;
                rightButton.setText(buttonTitle);
            }
        }


    }
    public void openDir(String path){



        if(dataList1.size()>0){

            dataList1.clear();
        }
        if(!path.equals("/")) {
            dataList1.add(new FileClass("..","上层文件夹",R.drawable.file_image, 0));
        }//root not need ..
        File f =new File(path);
        Logs.i("will start scan");
        if(!f.canRead()){

            Utils.changePathPermission(f.getPath());
            Logs.i("change dir permission to can read");
        }
        if(f.isDirectory()){

            File[] fs =f.listFiles();
            if(fs == null){
                Logs.i("nothing so I will get Root permission");


                fs =f.listFiles();//it counld be no permittion so should get root

                if(fs == null){
                    Logs.i("alread give root but still no files"+f.toString());
                    return ;
                }

            }
            String  info="";
            for(File file2 : fs){


                if(file2.isDirectory()){
                   info = getFileInfo(file2,0);
                    dataList1.add(new FileClass(file2.getName(),info,R.drawable.file_image,0));
                    //Logs.i("dir:"+file2.toString());

                }else{
                    info = getFileInfo(file2,1);
                    dataList1.add(new FileClass(file2.getName() ,info,R.drawable.text,1));
                   // Logs.i("file:"+file2.toString());
                }
               // Logs.i("name: "+file2.getName()+"info:"+info);


            }

        }

    }

    public String getFileInfo(File fileName,int type){

        String fileSizeString="";
        DecimalFormat df = new DecimalFormat("######0.00");
        if(type == 1) {
            try {


                FileInputStream fos = new FileInputStream(fileName);


                int fileSize = fos.available();
                if (fileSize < 1024) {

                    fileSizeString = fileSize + " B";
                } else if (fileSize >= 1024 && fileSize < 1024 * 1024) {

                    double size = fileSize * 100f / (100 * 1024 );
                    fileSizeString = df.format(size) + " KB";
                } else {
                    float size =  fileSize * 100f / (100 * 1024 * 1024 );
                    fileSizeString = df.format(size) + " MB";
                }
            }catch (Exception e){
                Logs.i("read failed"+fileName);
                e.printStackTrace();
            }

        }
        // getfile size
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(fileName.lastModified());
        String fileTime =format.format(date);//getfile time

        String  filerxw="";
        if(fileName.canRead()){
            filerxw+="r";
        }else{
            filerxw+="-";
        }
        if(fileName.canWrite()){
            filerxw+="w";
        }else{
            filerxw+="-";
        }
        if(fileName.canExecute()){
            filerxw+="x";
        }else{
            filerxw+="-";
        }


     return fileTime+" "+fileSizeString+" "+filerxw;

    }
    public void dataInit(){

        openDir(currentDir);
        String lbtitle=Utils.getPreStrValues("leftButton");
        String rbtitle=Utils.getPreStrValues("rightButton");
        if(lbtitle.equals("null") || lbtitle.equals("left")){

            lbtitle="left";
        }
        if(rbtitle.equals("null") || lbtitle.equals("right")){

            rbtitle="right";
        }
        leftButton.setText(lbtitle);
        rightButton.setText(rbtitle);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.leftButton:
                if(!currentDir.equals(leftDir)){
                    currentDir =leftDir;
                    openDir(currentDir);
                    adapter1.notifyDataSetChanged();
                }
                currentButton=0;
                LinearLayout.LayoutParams left;
                LinearLayout.LayoutParams right;
                currentTitle.setText(currentDir);
                left = (LinearLayout.LayoutParams)leftLine.getLayoutParams();
                left.height=10 ;
                leftLine.setLayoutParams(left);
                right = (LinearLayout.LayoutParams)rightLine.getLayoutParams();
                right.height=2;
                rightLine.setLayoutParams(right);

                break;
            case R.id.rightButton:
                if(!currentDir.equals(rightDir)){
                    currentDir =rightDir;
                    openDir(currentDir);
                    adapter1.notifyDataSetChanged();
                }
                currentButton=1;
                currentTitle.setText(currentDir);
                left = (LinearLayout.LayoutParams)leftLine.getLayoutParams();
                left.height=2;
                leftLine.setLayoutParams(left);
                right = (LinearLayout.LayoutParams)rightLine.getLayoutParams();
                right.height=10;
                rightLine.setLayoutParams(right);

                break;

            default:



        }
    }


    @Override
    protected void onStop() {

        Logs.i("sssssstop");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Logs.i("ddddddddestroy");

        Utils.setPreStrValues("leftDir",leftDir);
        Utils.setPreStrValues("rightDir",rightDir);
        Utils.setPreStrValues("leftButton",leftButton.getText().toString());
        Utils.setPreStrValues("rightButton",rightButton.getText().toString());

        super.onDestroy();
    }



}
